import React,{Component} from 'react';
import {View,Text,ScrollView,TouchableOpacity,Image,FlatList,RefreshControl,BackHandler,Alert} from 'react-native';
import CLNavigatorHeader from '../../component/CLNavigatorHeader';
import dwstyles from '../dwjs/styles';
import {naviPush , naviBack} from '../../navigatorApp/actions';
import {connect} from 'react-redux';
import themeconfig from '../../config/theme';
import Search from 'react-native-search-box';
import dw2styles from './styles'
import {getConfig,setConfigValue} from '../../utils/NativeUtil'
import {GetDepartMenber} from './actions'
import styles from '../historylist/styles'

const page = 0;
let hasMore = false;
class DWJS2 extends Component {
    static navigationOptions = ({ navigation, screenProps }) => ({
        header: <CLNavigatorHeader navigation={navigation} title="队伍建设"/>
    });

    constructor(props){
        super(props);
        this.state={
            level1:'',
            level2:'',
            userguid:'',
            isLoading: true,
            refreshing:false,
            pariState:'未配对',
            data:[],
            SearchText: ''
        }
        this._data = []
    }

    remenberInfo = (item) => {
        setConfigValue('pariState',item.DisplayName);
        setConfigValue('pariPersonName' , item.DisplayName);
        setConfigValue('pariPersonGuid',item.UserGuid);
        this.props.naviPush('Main',{})
        // this.props.naviBack();
    }

    componentDidMount(){
        getConfig('userguid',res=>{this.setState({userguid: res.userguid})})
        console.log('parmas',this.props.navigation.state)
        console.log('departmentcode',this.props.navigation.state.params.departmentcode);
        console.log('teaminfo',this.props.navigation.state.params.teaminfo);
        console.log('abovelevel',this.props.navigation.state.params.abovelevel);
        BackHandler.addEventListener('hardwareBackPress2',this.handlerback2)
        if(this.props.navigation.state.params.abovelevel!=''){
        this.setState({
            level1:this.props.navigation.state.params.abovelevel.InfoName,
            level2:this.props.navigation.state.params.teaminfo.InfoName
        })
        //根据点击入口来判断显示一二级名称
    }
        page=0;
        this.getData();
        // let params={
        //     SearchText:'',
        //     DeptCode:this.props.navigation.state.params.teaminfo.InfoCode,
        //     PageIndex:page
        // }
        // GetDepartMenber(params).then(res=>{
        //     console.log(res);
        //     this.setState({
        //         data:res
        //     })
        // }).catch(msg=>{
        //     console.log(msg);
        // })
    }

    handlerback2=()=>{

    }
    getData=()=>{
        let params={}
        if(this.props.navigation.state.params.teaminfo==''){
        params={
            SearchText:this.state.SearchText,
            DeptCode:this.props.navigation.state.params.departmentCode,
            PageIndex:page
        }
    }else{
      params={
        SearchText:this.state.SearchText,
        DeptCode:this.props.navigation.state.params.teaminfo.InfoCode,
        PageIndex:page
      }  
    }
    console.log('params',params)
    //上面主要判断是不是点配对入口进来的，点配对入口进来的，和点第二级部门进来的，参数不一样
        GetDepartMenber(params).then(res=>{
            console.log('GetDepartMenber' ,  res);
            if (res.length < 10) {
                hasMore = false
            } else {
                hasMore = true
            }
            if (page == 0) {
                this._data = res;
            } else {
                this._data = this._data.concat(res);
            }
            // if(res.length>0){
            this.setState({
                data:this._data,
                isLoading: false,
                refreshing: false,
            })
            // } else {
            // this.setState({
            //     data:this._data,
            //     isLoading: false,
            //     refreshing: false,
            // })
            // }
        }).catch(msg=>{
            console.log('GetDepartMenber' ,  msg);
        })
    }

    onEndReached = () => {
        console.log('hasMore');
        console.log(hasMore)
        if (hasMore) {
            page++;
            this.getData()
        }
    }

    onRefresh = () => { //刷新回调函数
        this.setState({
            refreshing: true,
            isLoading: true
        })
        page = 0;
        this.getData()
    }

    match=(item)=>{
        console.log(item);
        Alert.alert(
            '将与该队员匹配',
            '确认匹配吗',
            [
              {text: '确认', onPress: () => {this.remenberInfo(item);}},
              {text: '取消', onPress: () => console.log('取消')},
            ],
            { cancelable: false }
          )
    }
    //match函数是当入口为配对进来时，点击人员会弹窗提示是否匹配
    _renderItem=({item,index})=>{
        return(
            <TouchableOpacity onPress={(i)=>{i=index;console.log('index',i);this.props.navigation.state.params.abovelevel!=''?this.props.navigation.navigate('MemberInfo',{userguid:this.state.data[i].UserGuid}):this.match(item)}}>
            <View style={dwstyles.listitem}>
                <Image source={item.Sex=='男'?require('../../image/ico_man.png'):require('../../image/ico_women.png')} style={{width:30,height:30}} />
                <View style={dwstyles.rightContent}><Text style={dwstyles.rightContent_text}>{item.DisplayName}</Text><Text>{item.Mobile}</Text></View>
            </View>
            </TouchableOpacity>
        )
    }
    //这里会判断一下是不是配对入口进来的，是的话执行match，不是的话带userguid进行跳转，跳转到人员详情

    _keyExtractor = (item, index) => index;

    _listfooter=()=>{
        return (
            <View style={dwstyles.footerimg}>
            <Image source={require('../../image/pic_stop.png')} style={{width:'50%',height: 90 ,marginTop: 20}}/>
            </View>
        )
    }

    _loading=()=>{
        return(
            <View style={dwstyles.footerimg}>
            <Text>isLoading...</Text>
            </View>
        )
    }

    handleSearch=(e)=>{
        console.log('e',e);
        this.setState({
            SearchText : e
        })
        page=0;
        this.getData()
        
    }
    //点击搜索时执行的函数

    handleCancel=()=>{
        this.setState({
            SearchText:''
        })
        page=0;
        this.getData()
    }
    //点击取消时执行的函数
    render(){
        let depValue = ''
        if (this.props.navigation.state.params.teaminfo == ''){
            depValue = this.props.groupName
        }else{
            depValue =  this.state.level1  + '>' +this.state.level2
        }
        //根据入口判断是否显示第一级部门
        return (
            <View style={{flex:1,backgroundColor:'#eee'}}>
                <Search backgroundColor='#eee' placeholder='搜索队员' inputBorderRadius={18} searchIconCollapsedMargin={45} placeholderCollapsedMargin={33} inputStyle={{backgroundColor:themeconfig.grey3Color,width:'80%'}} cancelButtonTextStyle={{color:themeconfig.grey2Color}} onSearch={e=>this.handleSearch(e)} onCancel={this.handleCancel} cancelTitle='取消'/>
                <View style={styles.Titleline}>
                    {/* <Text style={[styles.Titleline_text1,{fontSize:16,borderBottomWidth:0,color:themeconfig.grey2Color,paddingBottom:10}]} onPress={()=>{this.props.naviPush('DWJS',{})}}>{depValue}</Text> */}
                    <Text style={[styles.Titleline_text1,{fontSize:16,borderBottomWidth:0,color:themeconfig.grey2Color,paddingBottom:10}]}>{depValue}</Text>
                    <Text style={styles.Titleline_text2}>{this.state.data.length}人</Text>
                </View>
                <FlatList data={this.state.data} renderItem={this._renderItem} keyExtractor={this._keyExtractor} ListFooterComponent={this.state.isLoading ? this._loading:this._listfooter} onEndReached={this.onEndReached} onEndReachedThreshold={0.2} onRefresh={this.onRefresh} refreshing={this.state.isLoading}></FlatList>
            </View>
        )
    }
    componentWillUnmount(){
        this._data=[];
        BackHandler.removeEventListener('hardwareBackPress2',this.handlerback2)
        this.setState({
            data:[]
        })
    }
}

const mapStateToProps = state => ({
    groupName: state.main.groupName
});

const mapDispatchToProps = dispatch => ({
    naviPush: (routeName, params) => {
        dispatch(naviPush(routeName, params));
    },
    naviBack: (routerName) => {
        dispatch(naviBack(routerName));
    }
});


export default connect(
    mapStateToProps,
    mapDispatchToProps
)(DWJS2);
